﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WpfSnqkGasAnalysis.Common;
using WpfSnqkGasAnalysis.IBusiness_impl;
using WpfSnqkGasAnalysis.IData;
using WpfSnqkGasAnalysis.Model;

namespace WpfSnqkGasAnalysis
{
    /// <summary>
    /// WindowGasEdit.xaml 的交互逻辑。气分析编辑
    /// </summary>
    /// 创建时间：2022-12-11 21:31:38。作者：王浩力
    public partial class WindowGasEdit : Window
    {
        public WindowGasEdit()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 被编辑的数据
        /// </summary>
        /// 创建时间：2022-12-11 21:53:46。 
        public Gas_analysis gas_Analysis = null;

        UserBusiness userBusiness = new UserBusiness();

        //下拉框数据初始化。创建时间：2022-12-6 14:23:37。作者：王浩力
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            ISource_dictDAL source_DictDAL = ServicesHelpter.GetService<ISource_dictDAL>();
            var all = source_DictDAL.GetAll();
            all = all.Where(g => g.D_stat == 1).ToList();

            //类别下拉框
            cmb_cate.ItemsSource = all.Where(g => g.Group_id.Equals("cate")).ToList();
            cmb_cate.DisplayMemberPath = "Item_name";
            cmb_cate.SelectedValuePath = "Id";

            //构造名称
            cmb_gouzao.ItemsSource = all.Where(g => g.Group_id.Equals("structure")).ToList();
            cmb_gouzao.DisplayMemberPath = "Item_name";
            cmb_gouzao.SelectedValuePath = "Id";

            //顶界层位
            cmb_topCeng.ItemsSource = all.Where(g => g.Group_id.Equals("cengwei")).ToList();

            //底界层位
            cmb_bottomCeng.ItemsSource = all.Where(g => g.Group_id.Equals("cengwei")).ToList();

            //取样位置
            var qylist = all.Where(g => g.Group_id.Equals("quyangLocation")).ToList();
            qylist.Insert(0, new Source_dict() { Id = 0, Item_name = "请选择" });
            cmb_quyang.ItemsSource = qylist;
            cmb_quyang.DisplayMemberPath = "Item_name";
            cmb_quyang.SelectedValuePath = "Id";

            //取样单位
            cmb_samping_company_name.ItemsSource = all.Where(g => g.Group_id.Equals("quyang")).ToList();
            cmb_samping_company_name.DisplayMemberPath = "Item_name";
            cmb_samping_company_name.SelectedValuePath = "Id";

            //分析单位
            cmb_analysis_company_name.ItemsSource = all.Where(g => g.Group_id.Equals("quyang")).ToList();
            cmb_analysis_company_name.DisplayMemberPath = "Item_name";
            cmb_analysis_company_name.SelectedValuePath = "Id";

            //取样条件
            cmb_samping_condition.ItemsSource = all.Where(g => g.Group_id.Equals("quyangCondition")).ToList();
            cmb_samping_condition.DisplayMemberPath = "Item_name";
            cmb_samping_condition.SelectedValuePath = "Id";

            //委托单位
            cmb_client.ItemsSource = all.Where(g => g.Group_id.Equals("quyang")).ToList();
            cmb_client.DisplayMemberPath = "Item_name";
            cmb_client.SelectedValuePath = "Id";

            //取样人
            var userList = userBusiness.GetAllUser();
            samping_user.ItemsSource = userList;
            samping_user.DisplayMemberPath = "User_real_name";
            samping_user.SelectedValuePath = "Id";

            //分析人
            analysis_user.ItemsSource = userList;
            analysis_user.DisplayMemberPath = "User_real_name";
            analysis_user.SelectedValuePath = "Id";

            //读取已经录入的数据， 添加时间：2022-12-11 21:53:25
            Task.Run(() =>
            {
                //查询校对的数据
                Gas_analysisBusiness gas_AnalysisBusiness = new Gas_analysisBusiness();
                var info = gas_AnalysisBusiness.Get(gas_Analysis.Id);

                this.Dispatcher.InvokeAsync(() =>
                {
                    HE.Text = info.He.ToKeepDecimal(4);
                    H2.Text = info.H2.ToKeepDecimal(4);
                    O2.Text = info.O2.ToKeepDecimal(4);
                    N2.Text = info.N2.ToKeepDecimal(4);
                    C1.Text = info.C1.ToKeepDecimal(4);
                    C6.Text = info.C6.ToKeepDecimal(4);
                    C3.Text = info.C3.ToKeepDecimal(4);
                    IC4.Text = info.Ic4.ToKeepDecimal(4);
                    NC4.Text = info.Nc4.ToKeepDecimal(4);
                    IC5.Text = info.Ic5.ToKeepDecimal(4);
                    NC5.Text = info.Nc5.ToKeepDecimal(4);
                    CO2.Text = info.CO2.ToKeepDecimal(4);
                    C2.Text = info.C2.ToKeepDecimal(4);
                    txt_totalSum.Text = info.All_calc_value.ToKeepDecimal(4);

                    ////是否脱硫   //添加时间：2023-1-10 14:00:53
                    //if (info.Is_desulphurization==1)
                    //{
                    //    this.radio_uoliu.IsChecked=true;
                    //    this.radio_weituoliu.IsChecked = false;
                    //}
                    //else
                    //{
                    //    this.radio_uoliu.IsChecked = false;
                    //    this.radio_weituoliu.IsChecked = true;
                    //}

                    txtYpbh.Text = info.Sample_no;
                    txtJh.Text = info.Well_no;
                    top_well_deep.Text = info.Top_well_deep.ToString();
                    bottom_well_deep.Text = info.Bottom_well_deep.ToString();
                    remark.Text = info.Remark;

                    //取样温度
                    samping_temperature.Text = info.Samping_temperature.ToString();

                    //油压，套压保留两位小数  //修改时间：2023-2-7 14:13:05。作者：王浩力
                    if (info.Oil_pressure.HasValue)
                    {
                        oil_pressure.Text = info.Oil_pressure.Value.ToString("F2");
                    }
                    if (info.Casing_pressure.HasValue)
                    {
                        casing_pressure.Text = info.Casing_pressure.Value.ToString("F2");
                    }

                    zong_s.Text = info.Zong_s.ToString();
                    water_point.Text = info.Water_point.ToString();

                    //取样时间             
                    DateTime samping_timeShow;
                    DateTime.TryParse(info.Samping_time, out samping_timeShow);
                    dateQuyangTime.SelectedDateTime = samping_timeShow;

                    //分析时间
                    DateTime analysis_timeShow;
                    DateTime.TryParse(info.Analysis_time, out analysis_timeShow);
                    analysis_time.SelectedDateTime = analysis_timeShow;

                    //移除输入焦点 2022-12-11 21:57:40
                    analysis_time.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));

                    txtH2S_input.Text = info.H2Smg.ToString();

                    //下拉框赋值
                    cmb_cate.SelectedValue = info.Cate;
                    cmb_gouzao.SelectedValue = info.Build_name;
                    cmb_topCeng.SelectedValue = info.Top_horizon;
                    cmb_bottomCeng.SelectedValue = info.Bottom_horizon;

                    //取样位置。//修改时间：2023-1-15 15:32:56。
                    if (Regex.IsMatch(info.Sampling_location, "^\\d{19}"))
                    {
                        cmb_quyang.SelectedValue = info.Sampling_location;
                    }
                    else
                    {
                        txt_quyang.Text = info.Sampling_location;
                    }

                    cmb_samping_company_name.SelectedValue = info.Samping_company_name;
                    cmb_analysis_company_name.SelectedValue = info.Analysis_company_name;

                    cmb_samping_condition.SelectedValue = info.Samping_condition;
                    cmb_client.SelectedValue = info.Client;
                    samping_user.SelectedValue = info.Samping_user_id;//取样人id
                    analysis_user.SelectedValue = info.Analysis_user_id; //分析人
                });
            });

        }


        //导入右侧指标数据
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            GasCommonMethod.ImportTxtReadValue(this, e);

            //计算总值
            GasCommonMethod.CalcTotalValue(this);
        }

        //编辑保存。//创建时间：2022-12-7 09:50:46。作者：王浩力
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            //取样位置  //添加时间：2023-1-15 15:39:39
            string sampling_location = cmb_quyang.SelectedValue?.ToString();
            if (!string.IsNullOrWhiteSpace(txt_quyang.Text))
            {
                // 取样位置。手动输入
                sampling_location = txt_quyang.Text.Trim();
            }

            Gas_analysis gas = new Gas_analysis()
            {
                Id = gas_Analysis.Id,
                Cate = cmb_cate.SelectedValue.ToString(),
                Sample_no = txtYpbh.Text,
                Well_no = txtJh.Text,
                Build_name = cmb_gouzao.SelectedValue.ToString(),
                Top_horizon = cmb_topCeng.SelectedValue.ToString(),
                Bottom_horizon = cmb_bottomCeng.SelectedValue.ToString(),
                Top_well_deep = top_well_deep.Text.ToMyDecimal(),
                Bottom_well_deep = bottom_well_deep.Text.ToMyDecimal(),
                Sampling_location = sampling_location,
                Samping_company_name = cmb_samping_company_name.SelectedValue.ToString(),
                Analysis_company_name = cmb_analysis_company_name.SelectedValue.ToString(),
                Remark = remark.Text,

                Samping_condition = cmb_samping_condition.SelectedValue.ToString(),//取样条件
                Client = cmb_client.SelectedValue.ToString(),
                Samping_time = dateQuyangTime.Text,//取样时间
                Analysis_time = analysis_time.Text,   //分析时间

                Samping_user = samping_user.Text,
                Analysis_user = analysis_user.Text,//分析人

                Samping_user_id = samping_user.SelectedValue.ToMyInt64(),    //取样人id
                Analysis_user_id = analysis_user.SelectedValue.ToMyInt64(),   //分析人id

                Samping_temperature = samping_temperature.Text.ToMyDecimal(),//取样温度
                Oil_pressure = oil_pressure.Text.ToMyDecimal(), //油压
                Casing_pressure = casing_pressure.Text.ToMyDecimal(),
                Zong_s = zong_s.Text.ToMyDecimal(),  //总硫
                Water_point = water_point.Text.ToMyDecimal(),  //水露点 

                All_calc_value = txt_totalSum.Text.ToMyDecimal(),//总值
                H2Smg = txtH2S_input.Text.ToMyDecimal(),
                He = HE.Text.ToMyDecimal(),
                H2 = H2.Text.ToMyDecimal(),
                O2 = O2.Text.ToMyDecimal(),
                N2 = N2.Text.ToMyDecimal(),
                C1 = C1.Text.ToMyDecimal(),
                C6 = C6.Text.ToMyDecimal(),
                C3 = C3.Text.ToMyDecimal(),
                Ic4 = IC4.Text.ToMyDecimal(),
                Nc4 = NC4.Text.ToMyDecimal(),
                Ic5 = IC5.Text.ToMyDecimal(),
                Nc5 = NC5.Text.ToMyDecimal(),
                CO2 = CO2.Text.ToMyDecimal(),
                C2 = C2.Text.ToMyDecimal()
            };
            //是否脱硫
            byte liuTuo = (bool)radio_uoliu.IsChecked ? (byte)1 : (byte)0;
            gas.Is_desulphurization = liuTuo;

            //保存
            Gas_analysisBusiness bll = new Gas_analysisBusiness();
            var result = bll.Edit(gas);
            ShowAlertHelpter.ShowAlert(result.Msg);
        }

        private void C2_KeyUp(object sender, KeyEventArgs e)
        {
            GasCommonMethod.CalcTotalValue(this);

            //输入的小数位满4位，自动切换到下一行输入  //添加时间：2023-2-7 12:41:11
            var input = sender as TextBox;
            if (!string.IsNullOrWhiteSpace(input.Text) && input.Text.IndexOf(".") >= 0 && input.Text.Split('.')[1].Trim().Length == 4)
            {
                input.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
            }
        }

        ///// <summary>
        ///// 计算总值
        ///// </summary>
        //private void CalcTotalValue()
        //{
        //    //计算总值        
        //    decimal? totalSum =
        //          +He.Text.ToMyDecimal2()
        //          + H2.Text.ToMyDecimal2()
        //          + O2.Text.ToMyDecimal2()
        //          + N2.Text.ToMyDecimal2()
        //          + C1.Text.ToMyDecimal2()
        //          + C6.Text.ToMyDecimal2()
        //          + C3.Text.ToMyDecimal2()
        //          + IC4.Text.ToMyDecimal2()
        //          + NC4.Text.ToMyDecimal2()
        //          + IC5.Text.ToMyDecimal2()
        //          + NC5.Text.ToMyDecimal2()
        //          + CO2.Text.ToMyDecimal2()
        //          + C2.Text.ToMyDecimal2();

        //    //总值
        //    txt_totalSum.Text = totalSum == null ? "" : totalSum.ToString();
        //}

        //检查输入字符串是否为数字 //创建时间：2022-12-7 15:16:20，作者：王浩力
        private void samping_temperature_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            var textElem = (sender as TextBox);

            //解决连续输入很多.
            if ((
                textElem.Text.StartsWith(".") || string.IsNullOrWhiteSpace(textElem.Text)
                || textElem.Text.Contains(".")
                ) && e.Text == ".")
            {
                e.Handled = true;
                return;
            }

            //禁止在0前面继续输入0
            int index = ((System.Windows.Controls.TextBox)e.Source).CaretIndex;
            if (textElem.Text.StartsWith("0.") && index == 0 && e.Text == "0")
            {
                e.Handled = true;
                return;
            }

            //不能输入非数字
            if (Regex.IsMatch(e.Text, @"[^\d+\.{0,1}\d+]+"))
            {
                e.Handled = true;
                return;
            }
        }

        //检查输入字符串是否为数字 //创建时间：2022-12-7 15:16:20，作者：王浩力
        private void samping_temperature_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            TextBox textBox = sender as TextBox;
            if (!string.IsNullOrWhiteSpace(textBox.Text))
            {
                if (textBox.Text == "0.0" || textBox.Text.StartsWith("00"))
                {
                    textBox.Text = textBox.Text.Replace("00", "");
                }
                if (!textBox.Text.StartsWith("0.") && Regex.IsMatch(textBox.Text, @"0+[1-9]+\.*\d+", RegexOptions.IgnoreCase))
                {
                    textBox.Text = textBox.Text.TrimStart('0');
                }

                //输入的不是小数或正整数           
                Regex regex = new Regex(@"[^\d+\.{0,1}\d+]", RegexOptions.IgnoreCase);
                textBox.Text = regex.Replace(textBox.Text, "");
            }
        }

        //退出  //添加时间：2023-2-7 10:51:05。作者：王浩力
        private void Exit_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }
}
